const rewire = require('rewire')
const Koa = require('koa')
const koaLogger = require('koa-logger')
const koaBody = require('koa-body')

function startApi(port, routes) {
  const app = new Koa()
  app.use(koaLogger())
  app.use(koaBody())

  for (let router of routes) {
    const ysRoute = router.makeRoute()
    app.use(ysRoute.routes()).use(ysRoute.allowedMethods())
  }

  app.listen(port)
}

function success(ctx, data = []) {
  ctx.body = JSON.stringify({msg: 'ok', data, code: 1000})
}

function fail(ctx, msg, code = 1001, data = []) {
  ctx.body = JSON.stringify({msg, data, code})
}

function routeFn(f) {
  return async function(ctx, next) {
    const rs = await f(ctx, next)
    ctx.body = rs
  }
}

module.exports = {success, fail, routeFn, startApi}
